//
//  ChatRoomHomeViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/8/3.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "ChatRoomHomeViewController.h"
#import "ARAudioPlayerManager.h"
#import "ARAudioRecordManager.h"

#import "CRMessage.h"
#import "CRMessageMaker.h"

@interface ChatRoomHomeViewController ()
<CRInputActionDelegate,CRInputViewDelegate,
CRSessionInteractorDelegate
>

proStrong NSTimer *timeDisplayTimer;

@end

@implementation ChatRoomHomeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //导航栏
    [self setUpNav];
    
    //消息 tableView
    [self setUpTableView];
    
    //输入框
    [self setUpInputView];
    
    
    
    
    
    self.session = [[CRSession alloc] initWithSessionId:@"1" type:CRSessionTypeP2P];
    
    
    
    
    WEAKSELF
    self.layout = [[CRSessionLayoutImpl alloc] initWithSession:self.session config:nil];
    self.layout.tableView = self.tableView;
    self.layout.inputView = self.sessionInputView;
    //没有逻辑处理的时候（纯UI的话，延时处理一下，不然safeAreaInsets会不正确）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.layout resetLayout];
    });
    
    
}

- (void)setUpNav {
    
    UIButton *returnBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    returnBtn.frame = CGRectMake(0, 0, 44, 44);
    returnBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [returnBtn setTitle:@"返回" forState:UIControlStateNormal];
    [returnBtn addTarget:self action:@selector(dismissAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:returnBtn];
    
    self.title = @"聊天室";
}

- (void)setUpTableView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.backgroundColor = kColorBgColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //self.tableViewTapGesture = [[UITapGestureRecognizer alloc] init];
    //self.tableViewTapGesture.cancelsTouchesInView = NO;
    //[self.tableViewTapGesture addTarget:self action:@selector(onTapTableView:)];
    //[self.tableView addGestureRecognizer:self.tableViewTapGesture];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:self.tableView];
    
}

- (void)setUpInputView {
    
    self.sessionInputView = [[CRInputView alloc] initWithFrame:CGRectMake(0, 0, self.view.width,0) config:nil];
    self.sessionInputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.sessionInputView setInputDelegate:self];
    [self.sessionInputView setActionDelegate:self];
    [self.sessionInputView refreshStatus:CRInputStatusText];
    [self.view addSubview:self.sessionInputView];
}

- (void)dismissAction {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - CRInputViewDelegate 输入栏代理（目前只有处理高度变化）

- (void)didChangeInputHeight:(CGFloat)inputHeight {
    
    [self.layout changeLayout:inputHeight];
}

#pragma mark - CRInputActionDelegate 输入栏事件代理

//- (BOOL)onTapMediaItem:(CRMediaItem *)item {
//    //cxx_test
//    return NO;
//}
//
//- (void)onTextChanged:(id)sender{}
//
- (void)onSendText:(NSString *)text atUsers:(NSArray *)atUsers {

    NSMutableArray *users = [NSMutableArray arrayWithArray:atUsers];
    if (self.session.sessionType == CRSessionTypeP2P) {
        [users addObject:self.session.sessionId];
    }

    CRMessage *message = [CRMessageMaker msgWithText:text];
    
    [self sendMessage:message];
}
//
//- (void)onSelectEmoticon:(CRInputEmoticon *)emoticon {
//
//
//}
//
//- (void)didReplyCancelled {
//
//
//}
//
//
//- (void)onSelectChartlet:(NSString *)chartletId
//                 catalog:(NSString *)catalogId{}

- (void)onCancelRecording {
    
    [[ARAudioRecordManager sharedInstance] stop];
    [self stopTimeDisplayTimer];
}

- (void)onStopRecording {
    
    [[ARAudioRecordManager sharedInstance] stop];
    [self stopTimeDisplayTimer];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[ARAudioPlayerManager sharedInstance] startWithPath:kRecordAudioCacheFilePath];
    });
}

- (void)onStartRecording {
    
    [[ARAudioRecordManager sharedInstance] start];
    [self beginTimeDisplayTimer];
}

#pragma mark - 消息收发接口
- (void)sendMessage:(CRMessage *)message {
    
    [self.interactor sendMessage:message toMessage:nil];
}

- (void)sendMessage:(CRMessage *)message completion:(void(^)(NSError * err))completion {
    
    [self.interactor sendMessage:message
                        toMessage:nil
                      completion:^(NSError *err) {
        if (completion) {
            completion(err);
        }
    }];
}

#pragma mark - 录音处理
- (void)beginTimeDisplayTimer {
    
    [self stopTimeDisplayTimer];
    
    WEAKSELF
    _timeDisplayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf dispayTimerString];
    }];
    [[NSRunLoop currentRunLoop]addTimer:_timeDisplayTimer forMode:NSRunLoopCommonModes];
}

- (void)stopTimeDisplayTimer {
    
    if (_timeDisplayTimer) {
        [_timeDisplayTimer invalidate];
        _timeDisplayTimer = nil;
    }
}

- (void)dispayTimerString {
    
    self.sessionInputView.audioRecordIndicator.recordTime = [ARAudioRecordManager sharedInstance].currentTime;
}

@end
